package com.zxtech.zzm.ftp

import com.zxtech.zzm.ftp.FTP.UploadProgressListener
import java.io.File
import java.io.IOException
import java.io.InputStream

class ProgressInputStream(
    private val inputStream: InputStream, private val listener: UploadProgressListener,
    private val localFile: File
) : InputStream() {
    private var progress: Long = 0
    private var lastUpdate: Long = 0
    private var closed = false
    @Throws(IOException::class)
    override fun read(): Int {
        val count = inputStream.read()
        return incrementCounterAndUpdateDisplay(count)
    }

    @Throws(IOException::class)
    override fun read(b: ByteArray, off: Int, len: Int): Int {
        val count = inputStream.read(b, off, len)
        return incrementCounterAndUpdateDisplay(count)
    }

    @Throws(IOException::class)
    override fun close() {
        super.close()
        if (closed) throw IOException("already closed")
        closed = true
    }

    private fun incrementCounterAndUpdateDisplay(count: Int): Int {
        if (count > 0) progress += count.toLong()
        lastUpdate = maybeUpdateDisplay(progress, lastUpdate)
        return count
    }

    private fun maybeUpdateDisplay(progress: Long, lastUpdate: Long): Long {
        var lastUpdate = lastUpdate
        if (progress - lastUpdate > TEN_KILOBYTES) {
            lastUpdate = progress
            listener.onUploadProgress(FTP.FTP_UPLOAD_LOADING, progress, localFile)
        }
        return lastUpdate
    }

    companion object {
        private const val TEN_KILOBYTES = 1024 * 10 //每上传10K返回一次
    }
}